/**
 * 在一个Object里面取出来key的值
 * @param {Object} obj 
 * @param {String} key a, obj.a
 */
export function getObjectValue(obj, key) {
    if(!obj) {
        return obj;
    } 
    let nameList = key.split('.');
    let temp = obj;
    for(let i = 0; i < nameList.length; i++) {
        if(temp[nameList[i]]) {
            temp = temp[nameList[i]];
        } else {
            return undefined; 
        }
    }
    return temp;
}


/**
 * 设置Object中的值
 * @param {Object} obj 
 * @param {String} key a, obj.a
 */
export function setObjectValue(obj, keys, value) {
    if(!obj) return obj
    let keyList = keys.split('.')
    let temp = obj;
    for(let i = 0; i < keyList.length -1; i++) {
        if(temp[keyList[i]]) {
            temp = temp[keyList[i]]
        }
    } 
    if(temp[keyList[keyList.length -1]] != null) {
        temp[keyList[keyList.length -1]] = value
    }
}


export function mergeAttr(obj1, obj2) {
    if(!obj1) {
        return clone(obj2)
    }
    if(!obj2) {
        return clone(obj1)
    }
    // 如果两个都不为空，则覆盖obj1的属性
    let result = {}
    let obj1Attrs = Object.getOwnPropertyNames(obj1);
    for(let i = 0; i < obj1Attrs.length; i++) {
        result[obj1Attrs[i]] = obj1[obj1Attrs[i]];
    }
    let obj2Attrs = Object.getOwnPropertyNames(obj2);
    for(let i = 0; i < obj2Attrs.length; i++) {
        result[obj2Attrs[i]] = obj2[obj2Attrs[i]];
    }
    return result;
}

export function easyClone(obj) {
    return JSON.parse(JSON.stringify(obj));
}

/**
 * 克隆算法
 * @param {*} obj 
 * @returns 
 */
function clone(obj) {
    if(obj instanceof Array) {
        cloneArray(obj)
    } else if(obj instanceof Object) {
        return cloneObject(obj);
    } else {
        return obj;
    }
}

function cloneObject(obj) {
    let result = {};
    // 如果需要克隆的属性是代理的，则直接返回代理
    let names = Object.getOwnPropertyNames(obj);
    for(let i = 0; i < names.length; i++) {
        result[names[i]] = clone(obj[names[i]]);
    }
}

function cloneArray(arr) {
    let result = [];
    for(let i = 0; i < arr.length; i++) {
        result.push(clone(arr[i]));
    }
    return result;
}

/**
 * 获取当前节点环境变量
 * @param {*} vm 
 * @param {*} vnode 
 * @returns 
 */
export function getEnvAttr(vm, vnode) {
    let result = mergeAttr(vm._data, vnode.env || {})
    result = mergeAttr(result, vm._computed || {})
    return result;
}